package com.dc.kylin.logbackdesensitization.config;

import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import com.dc.kylin.logbackdesensitization.utils.DesensitizationUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
@Component
public class DesensitizationPatternLayoutEncoder extends PatternLayoutEncoder {

    private static DesensitizationProperties properties;
    private static final AtomicBoolean initialized = new AtomicBoolean(false);

    @Autowired
    public void setProperties(DesensitizationProperties properties) {
        if (initialized.compareAndSet(false, true)) {
            DesensitizationPatternLayoutEncoder.properties = properties;
            log.info("DesensitizationPatternLayoutEncoder Desensitization pattern layout encoder initialized");
            log.info("DesensitizationPatternLayoutEncoder Desensitization properties: {}", properties);
            DesensitizationUtils.init(properties);
        }
    }

    @Override
    public void start() {
        // 创建并配置自定义 Layout
        DesensitizationPatternLayout patternLayout = new DesensitizationPatternLayout();
        patternLayout.setContext(context);
        patternLayout.setPattern(getPattern());
        patternLayout.setOutputPatternAsHeader(outputPatternAsHeader);
        patternLayout.start();

        // 设置 Layout
        this.layout = patternLayout;
        super.start();
    }

}
